package com.wxshare.sdk.remoting;

import com.alibaba.fastjson.JSONObject;
import com.wxshare.sdk.config.WXShareProperties;
import com.wxshare.sdk.execute.WXShareExecute;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.IOException;

@Slf4j
public class WXShareRemoting {
    private String type = "jsapi";

    @Autowired
    private WXShareProperties wxShareProperties;

    public String getAccessToken(){
        log.info("get access_token.....");
        log.info("grant_type : {}", wxShareProperties.getGrantType());
        log.info("appid : {}", wxShareProperties.getAppId());
        log.info("secret : {}", wxShareProperties.getSecret());

        Retrofit retrofit = new Retrofit.Builder().baseUrl(wxShareProperties.getBaseUrl())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Call<JSONObject> call =  retrofit.create(WXShareExecute.class).getAccessToken(wxShareProperties.getGrantType(),
                wxShareProperties.getAppId(), wxShareProperties.getSecret());

        Response<JSONObject> retrofitResponse = null;
        try {
            retrofitResponse = call.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!retrofitResponse.raw().isSuccessful()) {
            throw new RuntimeException("微信获取access_token 网络异常");
        }
        JSONObject jsonObject = retrofitResponse.body();
        if(!jsonObject.containsKey("access_token")){
            log.error("get access token error:{}", jsonObject);
            throw new RuntimeException("微信获取access_token 网络异常");
        }
        return jsonObject.getString("access_token");
    }

    public JSONObject getTicket(String accessToken){
        log.info("get ticket by access_token : {}", accessToken);

        Retrofit retrofit = new Retrofit.Builder().baseUrl(wxShareProperties.getBaseUrl())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Call<JSONObject> call =  retrofit.create(WXShareExecute.class).getTicket(accessToken, type);
        Response<JSONObject> retrofitResponse = null;
        try {
            retrofitResponse = call.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!retrofitResponse.raw().isSuccessful()) {
            throw new RuntimeException("微信获取ticket 网络异常");
        }
        return retrofitResponse.body();
    }

    public String getAppId(){
        return wxShareProperties.getAppId();
    }
}
